﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Reg
{
    /// <summary>CCPSIP_006：確認朋友關係（開通權限）API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。
    /// ConfirmAct = 確認或退回申請。確認請傳"Y"，退回請傳"N"。
    /// UserPhone = 新會員的手機門號。請由 confirm_list.ashx 回傳的 JSON 中取值。
    /// DeviceType = 新會員的裝置類別。請由 confirm_list.ashx 回傳的 JSON 中取值。

    public class confirm_act : IHttpHandler
    {
        private static string[] kAdminEmailList = { "ch_chou@ccp.com.tw", "hj_huang@ccp.com.tw",
                                                "mike_lin@ccp.com.tw", "chuck_lan@ccp.com.tw"
                                              };
        private const string kReportEmailAddr = "ccpsip_report@ccp.com.tw";

        private const string kSIPServerDefault = "118.163.125.205";
        private const string kHQMobileExtPrefix = SipKit.kHQMobileExtPrefix;//總公司行動分機前綴


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string ConfirmAct = req.Form["ConfirmAct"];//確認或退回申請
                string UserPhone = req.Form["UserPhone"];  //新會員的手機門號(含國碼)
                string DeviceType = req.Form["DeviceType"];//新會員的裝置類別

                try
                {
                    ConfirmAct = ConfirmAct.ToUpper();
                    if (ConfirmAct != "Y" && ConfirmAct != "N")
                        throw new Exception();

                    if (UserPhone.StartsWith("+"))
                        UserPhone = UserPhone.Substring(1);//去掉開頭的'+'
                }
                catch (Exception ex)
                {
                    ChrisKit.SkipVar(ex);
                    throw new Exception("Error_01: Parameter Error");//參數錯誤
                }


                //【02】取得SIP User資訊
                //
                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_02: Cannot identify this device");//無法識別此裝置
                }


                //【03】取得朋友的註冊資料
                //
                RegApplyInfo regInfo = OracleKitReg.getRegApplyInfo(UserPhone, DeviceType);
                if (regInfo == null)
                {
                    throw new Exception("Error_03: Register data not found");//找不到註冊資料
                }
                else if (regInfo.FriendPhone != userInfo.MobileNum
                  || regInfo.FriendCountry != userInfo.CountryCode)
                {
                    throw new Exception("Error_04: Not your friend");//朋友不是填你
                }


                if (ConfirmAct == "Y")
                {
                    //【04-1】確認申請 //

                    //【05】開通CCPSIP會員權限
                    //
                    string EmpID = regInfo.UserID;
                    string CCPExtHQ = SipKit.getCCPExtHQ(EmpID);
                    string SIP_Num = "";

                    if (string.IsNullOrEmpty(CCPExtHQ))
                    {
                        SIP_Num = OracleKitReg.GetGuestSIPNumber(regInfo.UserCountry, regInfo.UserPhone);

                        //【05-1】檢查客人的SIP號碼是否超出可用名額
                        //
                        UInt32 GuestNumber = Convert.ToUInt32(SIP_Num);
                        if (GuestNumber < 1940001 || GuestNumber > 1949999)
                        {
                            throw new Exception("Error_05: VIP Quota is full");//VIP帳號名額已滿
                        }
                        else if (GuestNumber > 1948999)
                        {
                            string mailSubject = "【警告】iSender VIP 號碼(194xxxx) 名額將滿";
                            string alertMsg = "Guest SIP Number = " + SIP_Num;
                            ChrisKit.SendCCPEmail(kReportEmailAddr, kAdminEmailList, null, mailSubject, alertMsg);
                        }
                    }
                    else
                    {
                        SIP_Num = kHQMobileExtPrefix + CCPExtHQ;

                        //【05-2】總公司分機可以有iPad專用號碼
                        //
                        if (DeviceType.StartsWith("iPad"))
                        {
                            if (AppleKit.isIPadMini(DeviceType))
                                SIP_Num = kHQMobileExtPrefix + CCPExtHQ + "3";
                            else
                                SIP_Num = kHQMobileExtPrefix + CCPExtHQ + "2";
                        }
                    }

                    OracleKitReg.ActivateRegUser(regInfo, SIP_Num);

                    //【06】開通IP PBX帳號
                    //
                    bool hadUser = IPPbxKitV3.HadUser(SIP_Num);
                    Dictionary<string, string> paramDict = null;

                    if (hadUser)
                    {
                        paramDict = IPPbxKitV3.GetUserData(SIP_Num);
                    }
                    else
                    {
                        paramDict = IPPbxKitV3.GetDefaultParamDict(kSIPServerDefault);
                        paramDict["phone"] = SIP_Num;
                    }

                    if (SipKit.isHQMobileExt(SIP_Num))
                    {
                        //[X]總公司來顯使用SIP主帳號 (不行，會變成自己打給自己)
                        //
                        paramDict["name"] = SIP_Num;
                    }
                    else
                    {
                        paramDict["name"] = SIP_Num;
                        paramDict["mobile"] = UserPhone;//行動電話
                    }

                    paramDict["name_cn"] = regInfo.FullName.Replace(" ", "_");//中文名稱(不能有空白)
                    paramDict["secret"] = SipKit.calcSipSecret(SIP_Num);//註冊密碼
                    paramDict["password"] = paramDict["secret"];//網頁密碼
                    paramDict["codec1"] = "ilbc";
                    paramDict["codec2"] = "gsm";
                    paramDict["codec3"] = "ulaw";
                    paramDict["video"] = "yes";//視訊通話
                    paramDict["dtmf"] = "rfc2833";
                    paramDict["nat"] = "yes";
                    paramDict["tls"] = "yes";


                    if (SipKit.isCCPUser(regInfo.UserType))
                    {
                        //依身分區分Dial Plan
                        if (OracleKitUser.isBoss(EmpID) || OracleKitUser.isTWManager(EmpID)
                          || OracleKitUser.isSalesman(EmpID) || OracleKitUser.isPH(EmpID) || OracleKitUser.isMIS(EmpID))
                        {
                            paramDict["cos"] = "National";
                        }
                        else if (regInfo.UserType == "CCP_HQ")
                            paramDict["cos"] = "Local";
                        else if (OracleKitUser.canCallOut(EmpID))
                            paramDict["cos"] = "Local";
                        else
                            paramDict["cos"] = "Internal";
                    }
                    else
                    {
                        paramDict["cos"] = "Internal";
                    }


                    if (hadUser)
                        IPPbxKitV3.UpdateUser(paramDict);
                    else
                        IPPbxKitV3.AddUser(paramDict);


                    //【07】建立 Cloud Disk User 資料夾
                    //
                    CloudDiskKit.InitUserFolder(SIP_Num);
                }
                else
                {
                    //【04-2】退回申請
                    //
                    OracleKitReg.CancelRegister("N", regInfo.UserCountry, regInfo.UserPhone, DeviceType);
                }


                //【99】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
